package com.vecspace.utils;

import java.io.StringWriter;
import java.io.Writer;
import java.util.Map;

import com.vecspace.utils.log.HLogger;

import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;

public class FreemarkerUtil {
	
	public FreemarkerUtil(){
		
	}
	
	/**根据freemarker模板和变量，生成正式文本*/
	public static String templateParser(String templateText, Map<String, Object> parameters)
			throws Exception {
		Configuration cfg = new Configuration(Configuration.VERSION_2_3_24);
		Template template;
		
		StringTemplateLoader stringLoader = new StringTemplateLoader();		
		stringLoader.putTemplate("dayuTemplate", templateText);
		
		cfg.setTemplateLoader(stringLoader);
		template = cfg.getTemplate("dayuTemplate", "utf-8");
		/* 创建数据模型 */
		Writer out = new StringWriter(1024 * 10);
		try{
			template.process(parameters, out);
		}catch(Exception ex){
			HLogger.DEFAULT().error(templateText);
			throw ex;
		}
		out.flush();
		String html = out.toString();//.replaceAll("[\\n\\r]", "");
		return html;
	}
	
	/**根据freemarker模板和变量，生成正式文本
	 * 
	 * @param templateText
	 * @param parameters
	 * @return
	 * @throws Exception 
	 * @author: wanghua
	 */
	public static String templateParser(String templateText, Object parameters) throws Exception {
		if(templateText == null) return null;
		Configuration cfg = new Configuration(Configuration.VERSION_2_3_24);
		Template template;
		
		StringTemplateLoader stringLoader = new StringTemplateLoader();		
		stringLoader.putTemplate("dayuTemplate", templateText);
		
		cfg.setTemplateLoader(stringLoader);
		template = cfg.getTemplate("dayuTemplate", "utf-8");
		/* 创建数据模型 */
		Writer out = new StringWriter(1024 * 10);
		try{
			template.process(parameters, out);
		}catch(Exception ex){
			//TLogger.DEFAULT().error(templateText);
			throw ex;
		}
		out.flush();
		String html = out.toString();//.replaceAll("[\\n\\r]", "");
		return html;
	}
	
	/**恢复被转义的freemarker的标签
	 * 比如将  $? --> $
	 *       #?  --> #
	 * @param html 
	 * @return
	 * @throws Exception 
	 * @author: wanghua
	 * @reviewer: 
	 */
	public static String recoverFtlMarker(String html){
		if(html == null) {
			return html;
		}
		html = html.replace("$?", "$");
		html = html.replace("#?", "#");
		return html;
	}
}